package org.example.bio.ch1;

import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class Server {
    public ServerSocket serverSocket;

    public Server(int port){
        try {
            serverSocket = new ServerSocket(port);
            System.out.println("启动服务端成功");
        } catch (IOException e) {
            System.out.println("启动服务端失败");
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        Server server = new Server(8000);
        try {
            server.acceptClientMsg();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void acceptClientMsg() throws IOException {
            while(!serverSocket.isClosed()) {
                Socket accept = serverSocket.accept();
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            System.out.println("启动客户端线程处理");
                            InputStream inputStream = accept.getInputStream();
                            while (true) {
                                int len;
                                byte[] data = new byte[1024];
                                while ((len = inputStream.read(data)) != -1) {
                                    String message = new String(data, 0, len);
                                    System.out.println("收到消息：" + message);
                                    accept.getOutputStream().write("收到消息：谢谢".getBytes());
                                }
                            }
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }).start();
            }


    }
}
